﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.AttributedModel;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.ReflectionModel;
using System.Reflection;
using Microsoft.Internal;

namespace System.ComponentModel.Composition.Caching.AttributedModel
{
    internal class CachedAttributedExportDefinition : ExportDefinition
    {
        public CachedAttributedExportDefinition(IDictionary<string, object> cache)
        {
            Assumes.NotNull(cache);

            this.Cache = cache;
        }

        public IDictionary<string, object> Cache
        {
            get;
            private set;
        }

        public override string ContractName
        {
            get { return this.Cache.ReadValue<string>(AttributedCacheServices.CacheKeys.ContractName); }
        }

        public override IDictionary<string, object> Metadata
        {
            get { return this.Cache.ReadDictionary<object>(AttributedCacheServices.CacheKeys.Metadata); }
        }

        public ExportingMember ToExportingMember(Type defaultType)
        {
            ReflectionMember member = GetMember(defaultType);

            return new ExportingMember(this, member);
        }

        internal ReflectionMember GetMember(Type defaultType)
        {
            return this.Cache.LoadReflectionMember(defaultType);
        }

        public static IDictionary<string, object> CreateCache(AttributedMemberExportDefinition definition)
        {
            Assumes.NotNull(definition);

            IDictionary<string, object> cache = new Dictionary<string, object>();
            cache.WriteValue(AttributedCacheServices.CacheKeys.ContractName, definition.ContractName);
            cache.WriteDictionary(AttributedCacheServices.CacheKeys.Metadata, definition.Metadata);
            cache.WriteReflectionItem(definition.Member, definition.Definition.PartType);

            return cache;
        }


    }
}
